import os
import tempfile
import pytest
from app import create_app
from app.models.db import get_db_connection, execute_query

@pytest.fixture
def app():
    """创建测试用Flask应用"""
    # 创建临时数据库文件
    db_fd, db_path = tempfile.mkstemp()
    
    # 配置测试环境
    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
        'SECRET_KEY': 'dev_key_for_testing',
        'WTF_CSRF_ENABLED': False,
        'DEBUG': True
    })
    
    # 创建测试数据库
    with app.app_context():
        _init_test_db()
    
    yield app
    
    # 清理资源
    os.close(db_fd)
    os.unlink(db_path)

def _init_test_db():
    """初始化测试数据库"""
    try:
        with get_db_connection() as conn:
            # 创建用户表
            execute_query(conn, """
                CREATE TABLE IF NOT EXISTS users (
                    id SERIAL PRIMARY KEY,
                    username VARCHAR(50) UNIQUE NOT NULL,
                    password VARCHAR(100) NOT NULL,
                    email VARCHAR(100) UNIQUE,
                    role VARCHAR(20) DEFAULT 'user',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    last_login TIMESTAMP
                )
            """)
            
            # 创建测试用户
            execute_query(conn, 
                "INSERT INTO users (username, password, role) VALUES (%s, %s, %s)",
                ('testuser', 'hashed_password', 'admin')
            )
            
            # 创建库存表
            execute_query(conn, """
                CREATE TABLE IF NOT EXISTS inventory (
                    id SERIAL PRIMARY KEY,
                    product_id VARCHAR(50) UNIQUE NOT NULL,
                    product_name VARCHAR(100) NOT NULL,
                    quantity INT NOT NULL DEFAULT 0,
                    unit VARCHAR(20) DEFAULT '件',
                    cost_price DECIMAL(10,2),
                    sale_price DECIMAL(10,2),
                    category VARCHAR(50),
                    supplier VARCHAR(100),
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            
            # 创建测试库存数据
            execute_query(conn, 
                "INSERT INTO inventory (product_id, product_name, quantity) VALUES (%s, %s, %s)",
                ('TEST001', '测试产品', 100)
            )
    except Exception as e:
        print(f"初始化测试数据库失败: {e}")
        raise

@pytest.fixture
def client(app):
    """测试客户端"""
    return app.test_client()

@pytest.fixture
def runner(app):
    """CLI测试运行器"""
    return app.test_cli_runner()

@pytest.fixture
def auth(client):
    """认证辅助函数"""
    class AuthActions:
        def login(self, username='testuser', password='testpassword'):
            return client.post(
                '/login',
                data={'username': username, 'password': password}
            )
        
        def logout(self):
            return client.get('/logout')
    
    return AuthActions()